package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author fanYuLe
 * @Date 2023/3/1 16:15
 * @Blog blog.fanYuLe.net/996.mba
 * @Description:
 */
@Component //登录权限拦截器
public class LoginCheckInterceptor implements HandlerInterceptor {
    //拦截方法

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取session中用户信息
        Employee currentEmp = (Employee) request.getSession().getAttribute(Constant.SESSION_EMPLOYEE);
        //2.判断是否登录，进行拦截
        if(currentEmp ==null){
            //2-1设置返回信息
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            //2-2转为json
            String json = JSON.toJSONString(resultInfo);
            //2-3返回
            response.getWriter().write(json);
            //拦截
            return false;
        }
        // 存储当前线程
        EmployeeHolder.set(currentEmp);
        //3.放行
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //从线程内移除
        EmployeeHolder.remove();
    }
}

